package com.qf.spring.aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.Arrays;

/**
 * 用户的5种增强方法都定义在这个类中
 */
@Aspect //声明当前类是一个增强类
@Component
public class UserAdvice2 {
    //把切入点表达式抽出来
    @Pointcut("execution(* com.qf.spring.aop.service..*.*(..))")
    public void pointCut(){}


    //前置增强 JoinPoint:连接点
    @Before("pointCut()")
    public void before(JoinPoint joinPoint){
        System.out.println("前置增强执行了。。。");
        Object target = joinPoint.getTarget();
        System.out.println("target = " + target);
        System.out.println("方法的名字" +joinPoint.getSignature().getName());
        Object[] args = joinPoint.getArgs();
        System.out.println("参数是:" + Arrays.toString(args));
    }

    @AfterReturning(value = "pointCut()",returning = "result")
    public Object afterReturning(Object result){
        System.out.println("后置增强执行了。。。");
        //result目标方法的返回值
        return result;
    }

    //最终增强
    @After(value = "pointCut()")
    public void after(){

        System.out.println("最终增强执行了。。。");
    }

    //决定目标方法是否继续执行
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint jp){
        Object proceed=null;
        try {
            //统计执行时间
            long startTime = System.currentTimeMillis();
            StopWatch stopWatch=new StopWatch();
            stopWatch.start();
            System.out.println("环绕增强执行了。。前。。");
            proceed = jp.proceed();
            System.out.println("环绕增强执行了。。后。。");
            long endTime = System.currentTimeMillis();
            System.out.println("业务方法的执行时间为:"+(endTime-startTime));
            stopWatch.stop();
            System.out.println("stopWatch = " + stopWatch);

        } catch (Throwable e) {
            e.printStackTrace();
        }
        return proceed;
    }
    @AfterThrowing(value = "pointCut()",throwing = "e")
    public void throwing(Exception e){
        System.out.println("异常抛出增强执行了。。。");
        System.out.println("抛出的异常是" + e.getMessage());
    }
}
